package com.ywj.ehcache;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.validator.internal.util.privilegedactions.GetResource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.ywj.ehcache.util.ExcelUtil;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * 初始化缓存数据示例
 * @author yweijian
 * @date 2018年7月5日
 * @version 1.0
 */
@Component
public class InitEhcacheDatas implements CommandLineRunner{

	@Override
	public void run(String... arg0) throws Exception {
		CacheManager cacheManager = EhcacheManager.getCacheManager();
		String path = GetResource.class.getClassLoader().getResource("datas.xls").getPath();
		File file = new File(path);
		String[][] datas = ExcelUtil.getData(file, 0);
		if(datas != null){
			for(int i = 0; i < datas.length; i++){
				String[] data = datas[i];
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", data[0]);
				map.put("title", data[1]);
				map.put("pubdoctime", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(data[2]));
				map.put("istimeout", Integer.parseInt(data[3]));
				map.put("depname", data[4]);
				Cache cache = cacheManager.getCache("com.ywj.cache.document");
				cache.remove(map.get("id"));
				cache.put(new Element(map.get("id"), map));
			}
		}
	}

}
